const path = require('path')
const defaultSettings = require('./src/settings.js')
const dayjs = require('dayjs')
const fs = require('fs')
const archiver = require('archiver')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || ''
const port = 8312 || process.env.port || process.env.npm_config_port || 9528
const currentDateAndTime = dayjs().format('YYYYMMDD')
const packageName = process.env.VUE_APP_SYS_NAME
const version = require('./package.json').version

module.exports = {
  publicPath: './',
  outputDir: process.env.NODE_ENV === 'test' ? 'dist' : `${packageName}-${currentDateAndTime}-V${version}`,
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,

  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          // 把px单位换算成rem单位
          require('postcss-pxtorem')({
            rootValue: 75, // 换算的基数(设计图750的根字体为32)
            selectorBlackList: ['.van', '.el-table', '.el-pagination', '.el-pager', '.el-form-item', '.el-radio', '.el-select', '.el-input', '.el-backtop', '.search-left', '.el-descriptions', '.el-badge', '.highcharts', '.upload-file-list'], // 要忽略的选择器并保留为px。
            // selectorBlackList: [],
            propList: ['*'], // 可以从px更改为rem的属性。
            minPixelValue: 2 // 设置要替换的最小像素值。
          })
        ]
      }
    }
  },
  chainWebpack(config) {
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    config.plugins.delete('prefetch')
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          elementUI: {
            name: 'chunk-elementUI', // 将elementUI单独拆分一个包
            priority: 20,
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // 兼容cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // 设置自定义组件
            minChunks: 3,
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      config.optimization.runtimeChunk('single')
    })
    config.when(process.env.NODE_ENV === 'production', (config) => {
      config
        .plugin('zipPlugin')
        .use(class {
          apply(compiler) {
            compiler.hooks.afterEmit.tap('ZipPlugin', () => {
              const currentDateAndTime = dayjs().format('YYYYMMDD')
              const outputDir = `${packageName}-${currentDateAndTime}-V${version}`
              const onlineContentFolder = path.join(__dirname, outputDir)
              // 创建输出文件夹
              if (!fs.existsSync(onlineContentFolder)) {
                fs.mkdirSync(onlineContentFolder)
              }
              // 将线上产物放入输出文件夹（这里假设 onlineContent 是一个文件或文件夹路径）
              // 例如：fs.copyFileSync(onlineContent, path.join(onlineContentFolder, 'outputFileName'));
              // 创建一个输出的 .zip 文件
              const outputZip = fs.createWriteStream(path.join(__dirname, `${outputDir}.zip`))
              const archive = archiver('zip', {
                zlib: { level: 9 } // 设置压缩级别
              })
              // 将输出流管道到 .zip 文件
              archive.pipe(outputZip)
              // 将线上产物文件夹添加到 .zip 文件中
              archive.directory(onlineContentFolder, outputDir)
              // 完成 .zip 文件的创建
              archive.finalize()
              console.log(`.zip 文件已生成：${outputDir}.zip`)
            })
          }
        })
    })
  },
  devServer: {
    port: port,
    open: true,
    disableHostCheck: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/HeBeiHaiYang': {
        target: 'http://lc.guo.lol:28080/',
        changeOrigin: true,
        pathRewrite: {
          '^/HeBeiHaiYang': '/HeBeiHaiYang'
        }
      }
    }
  }
}
